Page({
  data: {
    userInfo: null,
    roomId: '',
    qrcodeUrl: '',
    playModes: ['中式九球', '美式九球', '十六彩'],
    currentMode: '中式九球'
  },
  onLoad(query) {
    if (query.mode) {
      this.setData({ currentMode: query.mode });
    }
  },
  onGetUserInfo(e) {
    this.setData({ userInfo: e.detail.userInfo });
  },
  onCreateRoom() {
    // 生成房间号和二维码
    const roomId = Math.random().toString(36).substr(2, 8);
    this.setData({
      roomId,
      qrcodeUrl: `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${roomId}`
    });
    // 云开发写入房间数据
    if (wx.cloud && this.data.userInfo) {
      const db = wx.cloud.database();
      db.collection('rooms').add({
        data: {
          _id: roomId,
          mode: this.data.currentMode,
          playerA: this.data.userInfo,
          playerB: {},
          playerAReady: true,
          playerBReady: false,
          currentGame: 1,
          totalGames: 9,
          history: []
        }
      });
    }
  },
  onModeChange(e) {
    this.setData({ currentMode: this.data.playModes[e.detail.value] });
  }
});
